<?php

Yii::import('zii.widgets.grid.CDataColumn');

class CStatColumn extends CDataColumn
{
	
	const STAT_FUNC_SUM='sum';
	const STAT_FUNC_AVG='avg';
	const STAT_FUNC_COUNT='count';
	
	/**
	 * @var string the type of the attribute value. This determines how the attribute value is formatted for display.
	 * Valid values include those recognizable by {@link CGridView::formatter}, such as: raw, text, ntext, html, date, time,
	 * datetime, boolean, number, email, image, url. For more details, please refer to {@link CFormatter}.
	 * Defaults to 'text' which means the attribute value will be HTML-encoded.
	 */
	public $statFunc='sum';

	/**
	 * Initializes the column.
	 */
	public function init()
	{
		parent::init();
//		if($this->name===null && $this->value===null)
//			throw new CException(Yii::t('zii','Either "name" or "value" must be specified for CDataColumn.'));
	}
	
	/**
	 * Renders the footer cell.
	 */
	public function renderFooterCell($rows=null)
	{
		echo CHtml::openTag('td',$this->footerHtmlOptions);
		$this->renderFooterCellContent($rows);
		echo '</td>';
	}
	
	/**
	 * Renders the footer cell content.
	 * The default implementation simply renders {@link footer}.
	 * This method may be overridden to customize the rendering of the footer cell.
	 */
	protected function renderFooterCellContent($rows=null)
	{
		$data=$this->grid->dataProvider->data;
		if ($rows===null)
			$rows=array_keys($data);
		$cnt=count($rows);
		if ($cnt>0)
		{
			$result=0.0;
			foreach ($rows as $row)
			{
				switch ($this->statFunc)
				{
					case self::STAT_FUNC_SUM : 
						$result+= CHtml::value($data[$row],$this->name);
						break;
					case self::STAT_FUNC_AVG : 
						$result+= CHtml::value($data[$row],$this->name);
						break;
					case self::STAT_FUNC_COUNT : 
						$result++;
						break;
				}	
			}
			if ($this->statFunc===self::STAT_FUNC_AVG)
				$result = $result/$cnt;
			echo $result===0 ? '&nbsp;': $result;
		}
		else
			echo parent::renderFooterCellContent();
	}
	
}
